package com.epam.kulibaba.helpers.testSupport;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Reporter;

import com.epam.kulibaba.components.mainPage.ProductsContainer;
import com.epam.kulibaba.helpers.Class.Category;

public class CategoryListMainHelper {
	public static List<Category> categories = new ArrayList<Category>();
	
	
	public static List<Category> getCategoryListMain(ProductsContainer container) {
		try {
			Category category = null;
			String name;
			List<WebElement> itemCategories = container.getContainer()
					.findElements(By.cssSelector("*"));
			for (WebElement element : itemCategories) {
				if (element.getTagName().toLowerCase().equalsIgnoreCase("h1")) {
					name = element.findElement(By.cssSelector("a")).getText();
					category = new Category(element, name);
					categories.add(category);
					continue;
				}
				if (element.getTagName().toLowerCase().equalsIgnoreCase("a")) {
					if (category == null)
						throw new Exception("structure was changed");
					name = element.getText();
					category.categories.add(new Category(element, name));
				}
			}
		} catch (Exception e) {
			System.out.println("structure was changed");
		}
		return categories;
	}

	public static Category findCategory(ProductsContainer container,
			String nameCategory) {
		Reporter.log("Go to page Category - " + nameCategory);
		System.out.println(nameCategory);
		for (Category category : getCategoryListMain(container)) {			
			if (category.name.equalsIgnoreCase(nameCategory)) {
				return category;
			}
			for(Category subcategory : category.categories){
				if (subcategory.name.equalsIgnoreCase(nameCategory)) {
					return subcategory;
				}
			}
		}
		return null;
	}

	public static void goToCategory(ProductsContainer container,
			String nameCategory) {
		CategoryListMainHelper.findCategory(container, nameCategory).click();
	}

}
